"""用于管理和代码相关的配置"""
from flask import Flask, render_template, g
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from redis import StrictRedis
from config import config,Setlogging
from flask_wtf.csrf import generate_csrf
sr = None  # type: StrictRedis
db = SQLAlchemy()
def config_init(environmental):
    # 配置日志
    Setlogging(config[environmental])
    # 配置文件
    app = Flask(__name__)
    # 加载配置文件
    app.config.from_object(config[environmental])
    db.init_app(app)
    # 配置redis
    global sr
    sr = StrictRedis(host=config[environmental].REDIS_HOST, port=config[environmental].REDIS_PORT, decode_responses=True)
    # 配置Session的指定位置
    Session(app)
    # 开启CSRF保护，只能服务器的验证,已经帮我们做好了验证的操作，我们只需要往COOKIE中和表单中添加CSRF_TOKEN就行了
    CSRFProtect(app)
    # 添加过滤器
    from info.until.common import do_index_class
    app.add_template_filter(do_index_class,'index_class')
    # 给每个页面添加csrf_token
    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie("csrf_token", csrf_token)
        return response

    from info.until.common import outside
    @app.errorhandler(404)
    @outside
    def error(e):
        use= g.use
        data={
            "use":use.to_dict() if use else None
        }
        return render_template("404.html",data=data)
    # 将蓝图注册到应用程序上
    from .Codes.News import index_blu
    app.register_blueprint(index_blu)

    from .Codes.passport import passport_blu
    app.register_blueprint(passport_blu)

    from .Codes.details import news_blu
    app.register_blueprint(news_blu)

    from .Codes.profile import personal_blu
    app.register_blueprint(personal_blu)

    from .Codes.admin import admin_blu
    app.register_blueprint(admin_blu)

    return app